package com.bt.mes.brm.provider.service;

import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_ADD;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_DELETE;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_LIST_WHOLE;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_QUERY;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_UPDATE;
import static com.bt.mes.common.bean.def.GenericDef.E_XPBISOPE_NOT_FOUND_OPE;
import static com.bt.mes.common.bean.def.GenericDef.E_XPBISTOOL_NOT_FOUND_RECORDER;
import static com.bt.mes.common.bean.def.GenericDef.E_XPBISTOOL_RECORDER_ALREADY_EXIST;
import static com.bt.mes.common.bean.def.GenericDef.RETURN_CODE_OK;
import static com.bt.mes.common.bean.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.bt.mes.common.bean.def.GenericDef.RETURN_MESG_OK;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.bt.mes.brm.api.service.IXpbistoolService;
import com.bt.mes.brm.provider.tx.Xpbisope.XpbisopeI;
import com.bt.mes.brm.provider.tx.Xpbistol.XpbistolI;
import com.bt.mes.brm.provider.tx.Xpbistol.XpbistolIA;
import com.bt.mes.brm.provider.tx.Xpbistol.XpbistolO;
import com.bt.mes.brm.provider.tx.Xpbistol.XpbistolOA;
import com.bt.mes.common.dao.IBisOpeDao;
import com.bt.mes.common.dao.IBisToolDao;
import com.bt.mes.common.dao.IBisToolGrDao;
import com.bt.mes.common.util.JacksonUtil;
import com.bt.mes.common.util.MqOpe;
import com.bt.mes.common.util.Util;
import com.bt.table.ppt.Bis_ope;
import com.bt.table.ppt.Bis_opeId;
import com.bt.table.ppt.Bis_tool;
import com.bt.table.ppt.Bis_tool_gr;
import com.bt.table.ppt.Bis_tool_grId;

@Service("xpbistoolService")
public class XpbistoolService implements IXpbistoolService{
	private static final Logger logger = Logger.getLogger(XpbispathService.class);
	@Autowired
	private XpbistolI inTrx;
	
	@Autowired
	private XpbistolO outTrx; 
	
	
	@Autowired
	private IBisToolDao bisToolDao;
	
	@Autowired
	private IBisToolGrDao bisToolGrDao;
	
	@Autowired
	private IBisOpeDao bisOpeDao;
	
	@Autowired
	private MqOpe mqOpe;
	
	public String subMainProc(String strInMsg){
		String outMsg ="";
		try{
			inTrx = JacksonUtil.fromJson(strInMsg, XpbistolI.class);
			outTrx.setRtn_code(RETURN_CODE_OK);
			outTrx.setRtn_mesg(RETURN_MESG_OK);
			char action_flg = inTrx.getAction_flg().charAt(0);
			switch( action_flg ){
				case ACTION_FLG_QUERY      :  queryByCondition()  ; break;   
				case ACTION_FLG_ADD        :  addFnc()            ; break;
				case ACTION_FLG_UPDATE     :  updateFnc()         ; break;
				case ACTION_FLG_DELETE     :  deleteFnc()         ; break;
				case ACTION_FLG_LIST_WHOLE :  listAllFnc()        ; break;
				default                    :  errActionFnc();   
			}
			if( RETURN_CODE_OK.equals(outTrx.getRtn_code()) ){
				bisToolDao.flushCurSession();
			}else{
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}	
			
			
		}catch(Exception ex){
			outTrx.setTrx_id("XPBISTOL");
			outTrx.setType_id("O");
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg(ex.toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}finally{
			outMsg = JacksonUtil.toJSONStr(outTrx);
			logger.info(outMsg);
		}
		return outMsg;
	}
	public void addFnc(){

		outTrx.setTrx_id("XPBISTOL");
		outTrx.setType_id("O");
		XpbistolIA iary = inTrx.getIary().get(0);
		String tool_id = iary.getTool_id();
		Bis_tool queryBisOpe = getDataByKeyProc( tool_id );
		if(queryBisOpe!=null){
			outTrx.setRtn_code(E_XPBISTOOL_RECORDER_ALREADY_EXIST+"");
			outTrx.setRtn_code("Tool Already Exist");
			return ;
		}
		Bis_tool bis_tool = new Bis_tool();
		bis_tool.setTool_id(tool_id);
		bis_tool.setRep_unit_fk(iary.getRep_unit_fk());//TODO:从哪获取
		bis_tool.setData_pat_fk(iary.getData_pat_fk());//TODO:从哪获取
		bis_tool.setMes_id_fk(iary.getMes_id_fk());//TODO:从哪获取
		bis_tool.setTool_dsc(iary.getTool_dsc());
		bis_tool.setUnit_typ(iary.getUnit_typ());
		bis_tool.setRoot_tool_id(iary.getRoot_tool_id());
		bis_tool.setTool_cate(iary.getTool_cate());
		bis_tool.setBay_id(iary.getBay_id());
		bis_tool.setFloor_code(iary.getFloor_code());
		bis_tool.setMax_sht_cnt(iary.getMax_sht_cnt());
		bis_tool.setMax_sht_time(iary.getMax_sht_time());
		bis_tool.setTool_ip(iary.getTool_ip());
		bis_tool.setTool_trns_cate(iary.getTool_trns_cate());
		bis_tool.setEvt_user(iary.getEvt_user());
		bis_tool.setEvt_timestamp(Util.getCurrentTimestamp());
		bis_tool.setFab_id_fk(iary.getFab_id_fk());
		
		bisToolDao.save(bis_tool);
		//防止一个tool_id对应多个group的情况出现，绑定之前删除关系
		String hql = "FROM Bis_tool_gr where id.tool_id_fk ='" + tool_id +"'";
		List<Bis_tool_gr> bisToolGrList = bisToolGrDao.find(hql);
		if(bisToolGrList.size()>0){
			for(Bis_tool_gr bis_tool_gr:bisToolGrList){
				bisToolGrDao.delete(bis_tool_gr);
			}
		}
		String toolg_id = iary.getToolg_id();
		Bis_tool_grId toolGid = new Bis_tool_grId();
	    toolGid.setTool_id_fk(tool_id);
	    toolGid.setToolg_id(toolg_id);
	    Bis_tool_gr bis_tool_gr = bisToolGrDao.get(toolGid);
	    if( bis_tool_gr ==null){
	    	bis_tool_gr = new Bis_tool_gr();
	    	bis_tool_gr.setId(toolGid);
	    	bis_tool_gr.setValid_flg("Y");
	    	bisToolGrDao.save(bis_tool_gr);
	    }
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	
	}
	public void updateFnc(){

		XpbistolIA iary = inTrx.getIary().get(0);
		String tool_id = iary.getTool_id();
		Bis_tool bis_tool = getDataByKeyProc( tool_id );
		if(bis_tool==null){
			outTrx.setRtn_code(E_XPBISOPE_NOT_FOUND_OPE+"");
			outTrx.setRtn_code("not found ope");
			return ;
		}
		if(iary.getRep_unit_fk()!=null){
			bis_tool.setRep_unit_fk(iary.getRep_unit_fk());
		}
	    if(iary.getData_pat_fk()!=null){
	    	bis_tool.setData_pat_fk( iary.getData_pat_fk());
	    }
		if(iary.getMes_id_fk()!=null){
			bis_tool.setMes_id_fk(iary.getMes_id_fk());
		}
		if(iary.getTool_dsc()!=null){
			bis_tool.setTool_dsc(iary.getTool_dsc());
		}
		if(iary.getUnit_typ()!=null){
			bis_tool.setUnit_typ(iary.getUnit_typ());
		}
        if(iary.getRoot_tool_id()!=null){
        	bis_tool.setRoot_tool_id(iary.getRoot_tool_id());
        }
        if(iary.getTool_cate()!=null){
        	bis_tool.setTool_cate(iary.getTool_cate());
        }
        if(iary.getBay_id()!=null){
        	bis_tool.setBay_id(iary.getBay_id());
        }
        if(iary.getFloor_code()!=null){
        	bis_tool.setFloor_code(iary.getFloor_code());
        }
        if(iary.getMax_sht_cnt()!=null){
        	bis_tool.setMax_sht_cnt(iary.getMax_sht_cnt());
        }
        if(iary.getMax_sht_time()!=null){
        	bis_tool.setMax_sht_time(iary.getMax_sht_time());
        }
        if(iary.getTool_trns_cate()!=null){
        	bis_tool.setTool_trns_cate(iary.getTool_trns_cate());
        }
        if(iary.getTool_ip()!=null){
        	bis_tool.setTool_ip(iary.getTool_ip());
        }
        if(iary.getEvt_user()!=null){
        	bis_tool.setEvt_user(iary.getEvt_user());
        }
        if(iary.getFab_id_fk()!=null){
        	bis_tool.setFab_id_fk(iary.getFab_id_fk());
        }
        if(iary.getToolg_id()!=null){
        	String hql = "FROM Bis_tool_gr where id.tool_id_fk='"+tool_id+"'";
        	List<Bis_tool_gr> bis_tool_grList = bisToolGrDao.find(hql);
        	for(Bis_tool_gr bis_tool_gr: bis_tool_grList){
        		bisToolGrDao.delete(bis_tool_gr);
        	}
        	String toolg_id = iary.getToolg_id();
        	Bis_tool_grId toolGid = new Bis_tool_grId();
        	toolGid.setTool_id_fk(tool_id);
        	toolGid.setToolg_id(toolg_id);
	    	Bis_tool_gr new_bis_tool_gr = new Bis_tool_gr();
	    	new_bis_tool_gr.setId(toolGid);
	    	new_bis_tool_gr.setValid_flg("Y");
	    	bisToolGrDao.save(new_bis_tool_gr);
        }
        bis_tool.setEvt_timestamp(Util.getCurrentTimestamp());
        bisToolDao.update(bis_tool);
        outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		
	
	}
	public void deleteFnc(){

		XpbistolIA iary = inTrx.getIary().get(0);
		String tool_id = iary.getTool_id();
		Bis_tool bis_tool = getDataByKeyProc(tool_id);
		if(bis_tool==null){
			outTrx.setRtn_code(E_XPBISTOOL_NOT_FOUND_RECORDER+"");
			outTrx.setRtn_code("not found tool_id["+tool_id+"]");
			return ;
		}                                       
		bisToolDao.delete(bis_tool);
		String hql = "FROM Bis_tool_gr where id.tool_id_fk='"+tool_id+"'";
    	List<Bis_tool_gr> bis_tool_grList = bisToolGrDao.find(hql);
    	for(Bis_tool_gr bis_tool_gr: bis_tool_grList){
    		bisToolGrDao.delete(bis_tool_gr);
    	}
    	outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	
	}
	public void queryByCondition(){

		XpbistolIA iary = inTrx.getIary().get(0);
		/***
		 * 支持 按tool_id,unit_typ,tool_cate查询
		 * 支持 按ope_id查询,ope_id ==>tool_group==>tool_id
		 * ***/
		String tool_id  = iary.getTool_id();
		String hql ="FROM Bis_tool where 1=1 ";
		if(tool_id!=null){
			if(tool_id.indexOf('*')==-1){
				hql = hql + " and tool_id='" + tool_id + "'";
			}else{
				hql = hql + " and tool_id like '" + tool_id.replace('*', '%') + "'";
			}
		}
		if(iary.getUnit_typ()!=null){
			hql = hql + " and unit_typ='" + iary.getUnit_typ() +"'";
		}
		if(iary.getTool_cate()!=null){
			hql = hql +" and tool_cate='" +iary.getTool_cate()+"'";
		}
		if(iary.getOpe_id()!=null && iary.getOpe_ver()!=null){
			Bis_opeId opeId = new Bis_opeId();
			opeId.setOpe_id(iary.getOpe_id());
			opeId.setOpe_ver(iary.getOpe_ver());
			Bis_ope bis_ope = bisOpeDao.get(opeId);
			if(bis_ope==null){
				outTrx.setRtn_code(E_XPBISOPE_NOT_FOUND_OPE+"");
				outTrx.setRtn_mesg("NOT FOUND operation["+iary.getOpe_id()+"]");
				return ;
			}
//			String tool_gr = bis_ope.getToolg_id();
			hql = hql + " and tool_id in ( select id.tool_id_fk from Bis_tool_gr where " +
					"id.toolg_id ='"+bis_ope.getToolg_id() + "')";
			
		}
		
		List<Bis_tool> bisToolList = bisToolDao.find(hql);
		List<XpbistolOA> oaryList = new ArrayList<XpbistolOA>();
		for(Bis_tool bis_tool : bisToolList){
			XpbistolOA oary = new XpbistolOA();
			oary.setTool_id(bis_tool.getTool_id());
			oary.setRep_unit_fk(bis_tool.getRep_unit_fk());
			oary.setData_pat_fk(bis_tool.getData_pat_fk());
			oary.setMes_id_fk(bis_tool.getMes_id_fk());
			oary.setTool_dsc(bis_tool.getTool_dsc());
			oary.setUnit_typ(bis_tool.getUnit_typ());
			oary.setRoot_tool_id(bis_tool.getRoot_tool_id());
			oary.setTool_cate(bis_tool.getTool_cate());
			oary.setBay_id(bis_tool.getBay_id());
			oary.setFloor_code(bis_tool.getFloor_code());
			oary.setMax_sht_cnt(bis_tool.getMax_sht_cnt());
			oary.setMax_sht_time(bis_tool.getMax_sht_time());
			oary.setTool_trns_cate(bis_tool.getTool_trns_cate());
			oary.setTool_ip(bis_tool.getTool_ip());
			oary.setEvt_user(bis_tool.getEvt_user());
			oary.setFab_id_fk(bis_tool.getFab_id_fk());
			String hql2 = "FROM Bis_tool_gr where id.tool_id_fk='"+tool_id+"'";
	    	List<Bis_tool_gr> bis_tool_grList = bisToolGrDao.find(hql2);
	    	if(bis_tool_grList.size()>0){
	    		oary.setToolg_id(bis_tool_grList.get(0).getId().getToolg_id());
	    	}
	        oaryList.add(oary);
		}
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
	}
	public void listAllFnc(){

		List<XpbistolOA> oaryList = new ArrayList<XpbistolOA>();
		String hql = "FROM Bis_tool where 1=1";
		List<Bis_tool> bisToolList = bisToolDao.find(hql);
		for(Bis_tool bis_tool:bisToolList){
			XpbistolOA oary = new XpbistolOA();
			oary.setTool_id(bis_tool.getTool_id());
			oary.setTool_dsc(bis_tool.getTool_dsc());
			oary.setBay_id(bis_tool.getBay_id());
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	
	}
	public Bis_tool getDataByKeyProc(String tool_id){
		Bis_tool bis_tool = bisToolDao.get(tool_id);
		return bis_tool;
	}
	public void errActionFnc(){
		outTrx.setTrx_id("XPLSTDAT");
		outTrx.setType_id("O");
		outTrx.setRtn_code("0000009");
		outTrx.setRtn_mesg("Invalid Action_flg");
	}
	
}
